package com.paradise.phone.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.OrientationEventListener;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.paradise.api.FaceCall;
import com.paradise.api.FaceLogin;
import com.paradise.api.FacePhone;
import com.paradise.api.FacephoneListener;
import com.paradise.api.FacephonePreferences;
import com.paradise.phone.R;
import com.paradise.phone.fragment.CallFragment;
import com.paradise.phone.fragment.SettingFragment;
import com.paradise.phone.fragment.UserInfoFragment;
import com.paradise.phone.utils.ToastUtil;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionNo;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import org.linphone.core.LinphoneAuthInfo;
import org.linphone.core.LinphoneCall;
import org.linphone.core.LinphoneCore;
import org.linphone.core.LinphoneProxyConfig;

import java.util.List;

public class MainActivity extends BaseActivity
        implements FacephoneListener.FacephoneRegistrationStateListener,
        FacephoneListener.FacephoneCallStateListener, View.OnClickListener {

    private static final int INCOMMING_CALL = 0x001;
    private static final String INCOMMING_CALL_VIDEO = "video";
    private static final String INCOMMING_CALL_AUDIO = "audio";

    private static final int PERMISSOIN_CAMERA = 0;
    private static final int PERMISSOIN_PHONE = 1;
    private static final int PERMISSOIN_MICROPHONE = 2;
    private static final int PERMISSOIN_CALL_LOG = 3;

    private LinearLayout tvCall;
    private LinearLayout tvSetting;
    private CallFragment callFragment;
    private UserInfoFragment userInfoFragment;
    private SettingFragment settingFragment;

    public TextView getTvStatus() {
        return tvStatus;
    }

    private TextView tvStatus;
    private TextView tvUser;

    private RelativeLayout menuLeft;

    public DrawerLayout getNavigation() {
        return navigation;
    }

    private DrawerLayout navigation;
    private AlertDialog dialog;
    private String incommingCallType;

    private LinphoneAuthInfo authInfo;
    private AlertDialog dialogQuit;

    private RelativeLayout rlHead;

    private int mAlwaysChangingPhoneAngle = -1;
    private OrientationEventListener mOrientationHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        AndPermission.with(this)
                .requestCode(PERMISSOIN_CAMERA)
                .permission(Manifest.permission.CAMERA)
                .callback(this)
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                        AndPermission.rationaleDialog(MainActivity.this, rationale)
                                .setMessage("拒绝相机权限可能会影响视频通话").show();
                    }
                })
                .start();

        AndPermission.with(this)
                .requestCode(PERMISSOIN_PHONE)
                .permission(Manifest.permission.CALL_PHONE,
                        Manifest.permission.PROCESS_OUTGOING_CALLS)
                .callback(this)
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                        AndPermission.rationaleDialog(MainActivity.this, rationale)
                                .setMessage("拒绝电话权限可能会造成无法拨打电话").show();
                    }
                })
                .start();

        AndPermission.with(this)
                .requestCode(PERMISSOIN_MICROPHONE)
                .permission(Manifest.permission.RECORD_AUDIO)
                .callback(this)
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                        AndPermission.rationaleDialog(MainActivity.this, rationale)
                                .setMessage("拒绝麦克风权限可能会影响语音通话").show();
                    }
                })
                .start();

        AndPermission.with(this)
                .requestCode(PERMISSOIN_CALL_LOG)
                .permission(Manifest.permission.READ_EXTERNAL_STORAGE)
                .callback(this)
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                        AndPermission.rationaleDialog(MainActivity.this, rationale)
                                .setMessage("拒绝该权限可能会造成无法记录通话历史").show();
                    }
                })
                .start();

        initView();
        initEvent();

        if ((authInfo = FaceLogin.instance().getCurrentAuthInfo()) != null
                && getIntent().getStringExtra("INCOMMING_CALL") == null) {
            if (callFragment == null) {
                callFragment = new CallFragment();
            }
            switch2Fragment(callFragment);
            if (getIntent().getStringExtra("LOGIN") == null) {
                FaceLogin.instance().regist(this, getSharedPreferences("face_phone", Context.MODE_PRIVATE)
                                .getString("display_name", ""), authInfo.getUsername(),
                        getString(com.paradise.phone.R.string.password), getString(com.paradise.phone.R.string.domain), getString(com.paradise.phone.R.string.proxy), getString(com.paradise.phone.R.string.transport));
            } else {
                tvStatus.setText("在线");
                tvUser.setText(FacePhone.instance().getmLc().getDefaultProxyConfig().getIdentity());
            }
        }

        if (getIntent().getStringExtra("INCOMMING_CALL") != null) {

            if (FacePhone.instance().getmLc().getCurrentCall().getRemoteParams().getVideoEnabled()) {
                incommingCallType = INCOMMING_CALL_VIDEO;
            } else {
                incommingCallType = INCOMMING_CALL_AUDIO;
            }

            requestAnswer(FacePhone.instance().getmLc().getCurrentCall());

        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        FacePhone.instance().addCallStateListener(this);
    }

    private void initView() {
        tvCall = (LinearLayout) findViewById(R.id.tv_call);
        tvSetting = (LinearLayout) findViewById(R.id.tv_setting);
        menuLeft = (RelativeLayout) findViewById(R.id.menu_layout_left);
        navigation = (DrawerLayout) findViewById(R.id.navigation);
        tvStatus = (TextView) findViewById(R.id.tv_status);
        tvUser = (TextView) findViewById(R.id.tv_user);
        rlHead = (RelativeLayout) findViewById(R.id.rl_head);

        //startService(new Intent(this, FacephoneService.class));
    }

    private void initEvent() {
        tvCall.setOnClickListener(this);
        tvSetting.setOnClickListener(this);
        rlHead.setOnClickListener(this);
        navigation.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {

            }

            @Override
            public void onDrawerOpened(View drawerView) {
                tvUser.requestFocus();
            }

            @Override
            public void onDrawerClosed(View drawerView) {

            }

            @Override
            public void onDrawerStateChanged(int newState) {

            }
        });

        FacePhone.instance().addRegistrationStateListener(this);
        FacePhone.instance().addCallStateListener(this);
    }

    @Override
    public void registrationState(LinphoneCore linphoneCore, LinphoneProxyConfig linphoneProxyConfig, LinphoneCore.RegistrationState registrationState, String s) {
        if (registrationState.equals(LinphoneCore.RegistrationState.RegistrationOk)) {
            ToastUtil.showToast(this, "登陆成功！");
            tvStatus.setText("在线");
            tvUser.setText(linphoneProxyConfig.getIdentity());

            if (callFragment == null) {
                callFragment = new CallFragment();
            }
            switch2Fragment(callFragment);
        }
        if (registrationState.equals(LinphoneCore.RegistrationState.RegistrationProgress)) {
            ToastUtil.showToast(this, "登陆中...");
            tvStatus.setText("正在登陆");
            tvUser.setText("");
        }
        if (registrationState.equals(LinphoneCore.RegistrationState.RegistrationFailed)) {
            ToastUtil.showToast(this, "登陆失败！");
            tvStatus.setText("登陆失败");
            tvUser.setText("");
        }

        syncStatus();
    }

    @Override
    public void callState(LinphoneCore linphoneCore, LinphoneCall linphoneCall, LinphoneCall.State state, String s, boolean isAutoAnswer, boolean isVideoCall) {

        if (state.equals(LinphoneCall.State.OutgoingProgress)) {
            if (FacephonePreferences.instance().shouldInitiateVideoCall()) {
                incommingCallType = INCOMMING_CALL_VIDEO;
            } else {
                incommingCallType = INCOMMING_CALL_AUDIO;
            }

            switch2TalkingActivity();
        }

        if (state.equals(LinphoneCall.State.IncomingReceived)) {
            if (isAutoAnswer) {
                FaceCall.instance().acceptCall();
                if (isVideoCall)
                    incommingCallType = INCOMMING_CALL_VIDEO;
                else incommingCallType = INCOMMING_CALL_AUDIO;
                switch2TalkingActivity();
            }else if (isVideoCall){
                incommingCallType = INCOMMING_CALL_VIDEO;
                requestAnswer(linphoneCall);
            }else {
                incommingCallType = INCOMMING_CALL_AUDIO;
                requestAnswer(linphoneCall);
            }
        }
        if (state.equals(LinphoneCall.State.CallEnd)
                || state.equals(LinphoneCall.State.CallReleased)) {
            if (dialog != null) {
                dialog.dismiss();
            }
        }
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.tv_call:
                if (callFragment == null) {
                    callFragment = new CallFragment();
                }
                switch2Fragment(callFragment);
                navigation.closeDrawer(menuLeft);
                break;

            case R.id.tv_setting:
                if (settingFragment == null) {
                    settingFragment = new SettingFragment();
                }
                switch2Fragment(settingFragment);
                navigation.closeDrawer(menuLeft);
                break;

            case R.id.rl_head:
                if (userInfoFragment == null) {
                    userInfoFragment = new UserInfoFragment();
                }
                switch2Fragment(userInfoFragment);
                navigation.closeDrawer(menuLeft);
                break;
        }
    }

    private void requestAnswer(final LinphoneCall linphoneCall) {

        if (linphoneCall == null) {
            Log.d("flag->", "MainActivity.java(requestAnswer:223)->" + "call is null");
            return;
        }
        String type;
        if (incommingCallType == INCOMMING_CALL_AUDIO) {
            type = "音频";
        } else {
            type = "视频";
        }

        View view = LayoutInflater.from(this).inflate(R.layout.dialog_incomming_call, null);
        ImageView ivHangup = (ImageView) view.findViewById(R.id.iv_dialog_hang_up);
        ImageView ivAcceptCall = (ImageView) view.findViewById(R.id.iv_dialog_accept_call);
        TextView tvRemote = (TextView) view.findViewById(R.id.tv_remote);
        if (TextUtils.isEmpty(linphoneCall.getRemoteAddress().getDisplayName())) {
            tvRemote.setText(linphoneCall.getRemoteAddress().getUserName() + "," + type + "来电");
        } else {
            tvRemote.setText(linphoneCall.getRemoteAddress().getDisplayName() + "," + type + "来电");
        }
        ivHangup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FaceCall.instance().terminateCurrentCall();

                ToastUtil.showToast(MainActivity.this, "挂断电话");
            }
        });

        ivAcceptCall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FaceCall.instance().acceptCall();
                switch2TalkingActivity();
                dialog.dismiss();
                if (navigation.isDrawerOpen(menuLeft)) {
                    navigation.closeDrawer(menuLeft);
                }
            }
        });

        if (dialog == null) {

            dialog = new AlertDialog.Builder(this, R.style.IncommingCallDialog)
                    .setView(view)
                    .create();

            dialog.setCancelable(false);
        }
        if (!dialog.isShowing()) {
            dialog.show();
        }
    }

    private void switch2TalkingActivity() {
        startOrientationSensor();

        FacePhone.instance().removeCallStateListener();
        if (dialog != null) {
            dialog.dismiss();
        }

        Intent intent = new Intent(this, TalkingAcitvity.class);
        intent.putExtra("INCOMMING_CALL_TYPE", incommingCallType);
        startActivity(intent);
    }

    private void switch2Fragment(Fragment fragment){
        getFragmentManager().beginTransaction()
                .replace(com.paradise.phone.R.id.fl_fragment_container, fragment)
                .commit();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                View view = LayoutInflater.from(this).inflate(R.layout.ask_is_hang_up, null);
                TextView tvNo = view.findViewById(R.id.tv_ask_no);
                TextView tvYes = view.findViewById(R.id.tv_ask_yes);
                TextView tvTitle = view.findViewById(R.id.tv_title);
                tvTitle.setText("确定要退出FacePhone?");
                tvNo.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialogQuit.dismiss();
                    }
                });
                tvYes.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        System.exit(0);
                    }
                });

                if (dialogQuit == null) {
                    dialogQuit = new AlertDialog.Builder(this, R.style.IncommingCallDialog)
                            .setView(view)
                            .create();
                }

                if (!dialogQuit.isShowing()) {
                    dialogQuit.show();
                }

                break;
        }
        return false;
    }

    public String getStatus() {
        return tvStatus.getText().toString();
    }

    /**
     * 同步登陆状态到Fragment
     */
    private void syncStatus(){
        if (callFragment != null){
            //ToastUtil.showToast(MainActivity.this, "同步状态");
            callFragment.syncStatusFromActivity();
        }
    }


    private class LocalOrientationEventListener extends OrientationEventListener {
        public LocalOrientationEventListener(Context context) {
            super(context);
        }

        @Override
        public void onOrientationChanged(final int o) {
            if (o == OrientationEventListener.ORIENTATION_UNKNOWN) {
                return;
            }

            int degrees = 270;
            if (o < 45 || o > 315)
                degrees = 0;
            else if (o < 135)
                degrees = 90;
            else if (o < 225)
                degrees = 180;

            if (mAlwaysChangingPhoneAngle == degrees) {
                return;
            }
            mAlwaysChangingPhoneAngle = degrees;

            org.linphone.mediastream.Log.d("Phone orientation changed to ", degrees);
            int rotation = (360 - degrees) % 360;
            LinphoneCore lc = FacePhone.instance().getmLc();
            if (lc != null) {
                lc.setDeviceRotation(rotation);
                LinphoneCall currentCall = lc.getCurrentCall();
                if (currentCall != null && currentCall.cameraEnabled() && currentCall.getCurrentParamsCopy().getVideoEnabled()) {
                    lc.updateCall(currentCall, null);
                }
            }
        }
    }

    /**
     * Register a sensor to track phoneOrientation changes
     */
    private synchronized void startOrientationSensor() {
        if (mOrientationHelper == null) {
            mOrientationHelper = new LocalOrientationEventListener(this);
        }
        mOrientationHelper.enable();
    }

    @PermissionNo(PERMISSOIN_CAMERA)
    private void cameraPermissionDenied(List<String> deniedPermissions){
        ToastUtil.showToast(this, "相机权限被拒绝，可能会影响你的视频通话");
    }

    @PermissionNo(PERMISSOIN_MICROPHONE)
    private void microphonePermissionDenied(List<String> deniedPermissions){
        ToastUtil.showToast(this, "麦克风权限被拒绝，可能会影响你的语音通话");
    }

    @PermissionNo(PERMISSOIN_PHONE)
    private void phonePermissionDenied(List<String> deniedPermissions){
        ToastUtil.showToast(this, "电话权限被拒绝，可能造成无法拨打电话");
    }


}
